package main

import (
	"fmt"
	"log"
	"net/rpc/jsonrpc"
	"time"

	"rpc/api"
)

func handler(c chan bool, index, length int) {
	fmt.Println("Start ", index)

	client, err := jsonrpc.Dial("tcp", "127.0.0.1:9999")
	if err != nil {
		log.Println("Client connect error :" + err.Error())
	}
	defer client.Close()
	args := &api.Person{
		Name: "Jack",
		Age:  18,
	}
	var reply string

	//ServerMethodName = ServiceName(default struct name or register name) + CalledMethodName
	var serverMethodName = "Echo.Hello"

	//同步调用
	for i := length - 1; i >= 0; i-- {
		err = client.Call(serverMethodName, args, &reply)
		if err != nil {
			log.Println("RPC server call error :" + err.Error())
		} else {
			//		fmt.Printf("Synchronous Server API name=%s args=%v reply=%s\n", serverMethodName, args, reply)
		}
		time.Sleep(time.Duration(8) * time.Millisecond)
	}
	c <- true
}

func main() {
	var length = 500
	var rschan = make([]chan bool, length)

	var start = time.Now()
	for i := 0; i < length; i++ {
		rschan[i] = make(chan bool)
		go handler(rschan[i], i, length)
	}
	for _, c := range rschan {
		b := <-c
		if b {
			close(c)
		}
	}
	var end = time.Now()
	fmt.Printf("Const time %vms. \n", end.Sub(start).Nanoseconds()/1000000)
}
